﻿using GalaSoft.MvvmLight.CommandWpf;
using SpreadsheetGear.Windows.Controls;
using SpreadsheetGear;
using SpreadsheetGear.Commands;

namespace WPFWorkbookDesigner.Model.Commands
{
    public static class InsertMenu
    {
        public static RelayCommand<WorkbookView> InsertWorksheetCommand { get; } 
            = new RelayCommand<WorkbookView>(InsertWorksheet);
        public static RelayCommand<WorkbookView> InsertOrDeletePageBreaksCommand { get; } 
            = new RelayCommand<WorkbookView>(InsertOrDeletePageBreaks);

        private static void InsertWorksheet(WorkbookView view)
        {
            view.Dowork(v =>
            {
                var newSheet = v.ActiveWorkbook.Worksheets.Add();
                newSheet.Select();
            });
        }

        private static void InsertOrDeletePageBreaks(WorkbookView view)
        {
            IWorksheet sheet = view.ActiveWorksheet;
            IVPageBreaks vb = sheet.VPageBreaks;
            IHPageBreaks hb = sheet.HPageBreaks;
            view.Dowork(v =>
            {
                if (vb.Count != 0 && hb.Count != 0)
                {
                    for (int i = 0; i < vb.Count; i++)
                    {
                        vb[i].Delete();
                        hb[i].Delete();
                        i--;
                    }
                }
                else
                {
                    IRange r = v.RangeSelection;
                    if (r.Row == 0 || r.Column == 0)
                        return;
                    vb.Add(v.RangeSelection);
                    hb.Add(v.RangeSelection);
                }
            });
        }
    }
}